"use client";
import { Card, Button, message, Space, Tag } from "antd";
import Title from "antd/es/typography/Title";
import TagList from "@/components/TagList";
import MdViewer from "@/components/MdViewer";
import useAddUserSignInRecord from "@/hooks/useAddUserSignInRecord";
import { useEffect, useState } from "react";
import { EyeOutlined, EyeInvisibleOutlined, StarOutlined, StarFilled } from "@ant-design/icons";
import { favoriteQuestionUsingPost, unfavoriteQuestionUsingPost, isQuestionFavoritedUsingGet } from "@/api/questionFavoriteController";
import { useRouter } from "next/navigation";
import "./index.css";

interface Props {
  question: API.QuestionVO;
  isFavorite?: boolean;
  onFavoriteChange?: (isFavorite: boolean) => void;
}

/**
 * 题目卡片
 * @param props
 * @constructor
 */
const QuestionCard = (props: Props) => {
  const { question, isFavorite: initialIsFavorite = false, onFavoriteChange } = props;
  const [showAnswer, setShowAnswer] = useState(false);
  const [isFavorite, setIsFavorite] = useState(initialIsFavorite);
  const [favoriteLoading, setFavoriteLoading] = useState(false);
  const router = useRouter();

  // 签到
  useAddUserSignInRecord();

  // 获取收藏状态
  useEffect(() => {
    const checkFavoriteStatus = async () => {
      if (!question.id) return;
      try {
        const res = await isQuestionFavoritedUsingGet({
          questionId: question.id,
        });
        if (res.data !== undefined) {
          setIsFavorite(Boolean(res.data));
          onFavoriteChange?.(Boolean(res.data));
        }
      } catch (e) {
        console.error("获取收藏状态失败", e);
      }
    };
    checkFavoriteStatus();
  }, [question.id]);

  // 处理收藏/取消收藏
  const handleFavorite = async () => {
    if (favoriteLoading || !question.id) {
      return;
    }
    setFavoriteLoading(true);
    try {
      if (isFavorite) {
        await unfavoriteQuestionUsingPost({
          questionId: question.id,
        });
        message.success("取消收藏成功");
      } else {
        await favoriteQuestionUsingPost({
          questionId: question.id,
        });
        message.success("收藏成功");
      }
      setIsFavorite(!isFavorite);
      onFavoriteChange?.(!isFavorite);
    } catch (e: any) {
      message.error(isFavorite ? "取消收藏失败" : "收藏失败");
    }
    setFavoriteLoading(false);
  };

  return (
    <div className="question-card">
      <Card
        title={question.title}
        extra={
          <Button 
            type="text" 
            onClick={handleFavorite}
            loading={favoriteLoading}
            icon={isFavorite ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
          >
            {isFavorite ? "已收藏" : "收藏"}
          </Button>
        }
      >
        <p>{question.content}</p>
        <Space>
          {question.tagList?.map((tag: string) => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </Space>
      </Card>
      <div style={{ marginBottom: 16 }} />
      <Card 
        title="推荐答案"
        extra={
          <Button 
            type="text" 
            icon={showAnswer ? <EyeInvisibleOutlined /> : <EyeOutlined />}
            onClick={() => setShowAnswer(!showAnswer)}
          >
            {showAnswer ? "隐藏题解" : "查看题解"}
          </Button>
        }
      >
        {showAnswer ? (
          <MdViewer value={question.answer} />
        ) : (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <Button 
              type="primary" 
              icon={<EyeOutlined />}
              onClick={() => setShowAnswer(true)}
            >
              点击查看题解
            </Button>
          </div>
        )}
      </Card>
    </div>
  );
};

export default QuestionCard;
